package com.hfi.alibaba.timertask;

import org.junit.Test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author ChangLiang
 * @date 2019/7/2
 */
public class ScheduledExecutorServiceTest {

    private static ThreadLocal<Long> threadLocalCount = ThreadLocal.withInitial(() -> 0L);

    @Test
    public void test() {
        Runnable runnable = () -> {
            threadLocalCount.set(threadLocalCount.get() + 1);
            System.out.println("thread 1 -- " + threadLocalCount.get());
        };

        Runnable runnable2 = () -> {
            threadLocalCount.set(threadLocalCount.get() + 1);
            if (threadLocalCount.get().equals(6L)) {
                int a = 1 / 0;
            }
            System.out.println("thread 2 -- " + threadLocalCount.get());
        };

        // 看起来其用法也是一个线程来驱动的
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        scheduledExecutorService.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
        scheduledExecutorService.scheduleAtFixedRate(runnable2, 1, 1, TimeUnit.SECONDS);

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 与TimerTask类似，其也是使用一个线程来执行这两个任务的
        // 不同的是 thread2 由于抛出了没有捕获的异常 退出了 而且并没有抛出异常堆栈
        // 但是 thread1 仍旧执行完成
    }
}
